﻿#pragma once

#include <QObject>
#include "./Frameworks/EquipmentAction.h"
#include "../Shared/ModbusEvent.h"

class QModbusTcpClient;
class ModbusClient;

enum class WorkLocation : int
{
	RemoteController = 0,	//未知远程
	GoundController = 1,	//地面模式
	WorkPlaceController = 2	//井下工作面
};

class ModbusClientProxy : public QObject, public EquipmentAction , public ModbusEvent
{
	Q_OBJECT
	using this_type = ModbusClientProxy;
	using me_msg_func = std::function<void(QJsonObject const&)>;
public:
	inline static QStringView const Identity = L"modbusClient";
	void update(QJsonObject const& msg) override;
	void send(QJsonObject const& msg) override;
	void setMediator(AbstruactEventMediator* mediator) override;
	QStringView identity() const override;
	bool connectDevice(QJsonObject const& obj);
	QVariant request(QJsonObject const& obj, QStringView const requester) override;
	void send(QJsonObject const& msg, QStringView to) override;
	void setLocation(WorkLocation location);
	//ModbusEvent 接口
public:
	bool read(QModbusClient* client, int device) override;
	bool update(QModbusClient* client, QModbusDataUnit const& msg, int device) override;
	bool write(QModbusClient* client, QModbusDataUnit const& msg, int device) override;
private slots:
	void onConnected();
	void onDisconnected();
	void onConnectClosed();
	void onSuspectNetwork(int level);
	void onReportLogs(QString const& logs, int lev);
private:
	void transmit(QJsonObject const& msg);
	void processRegister(int startAddress, QVector<quint16> values);
	void fillRegisterZero();
public:
	ModbusClientProxy(QObject *parent = nullptr);
	~ModbusClientProxy();
private:
	AbstruactEventMediator* m_mediator = nullptr;
	ModbusClient* m_modbusCli;
	std::map<QStringView, me_msg_func> m_msgMap;
	WorkLocation m_location = WorkLocation::RemoteController;
};
